import { delay, postMsg } from '../utils.js';
import { CWBB_MONTH_JSON } from './data/cwbbjson.js';

async function fillC0019Grid(frameDoc, data, xh, left = true, row = 3) {
  for (let i = 0; i < xh.length; i++) {
    let uid = `${row}`.padStart(2, '0');
    const dataItem = data.find((x) => x.reportItemUuid === `P14$${uid}`);
    row++;

    const ewbhxh = xh[i];

    const key1 = left ? 'zcfzb1' : 'zcfzb3';
    const key2 = left ? 'zcfzb2' : 'zcfzb4';

    // 期末余额
    if (dataItem.colValue1) {
      const el = $(`[data-ewbhxh="${ewbhxh}"].${key1}`, frameDoc);
      el.val(dataItem.colValue1).trigger('input').trigger('change');
      await delay(200);
    }

    // 上年年末余额
    if (dataItem.colValue2) {
      const el = $(`[data-ewbhxh="${ewbhxh}"].${key2}`, frameDoc);
      el.val(dataItem.colValue2).trigger('input').trigger('change');
      await delay(200);
    }
  }
}

/**
 * 填写资产负债表 企业会计准则
 */
export async function fillQyZcfz(data) {
  const thisYearData = data.data.balance;

  const layerDoc = $('.layui-layer-content iframe')[0].contentWindow.document;
  // 是否是未执行
  let isWzx = true;
  let frame = $('iframe[name="C00119"]', layerDoc); // 未执行
  if (!frame || frame.length === 0) {
    frame = $('iframe[name="A06893"]', layerDoc); // 已执行
    isWzx = false;
  }
  const frameDoc = frame[0].contentWindow.document;

  // Array.from(document.querySelectorAll('[name="zcxmmc"]')).map(x=>x.getAttribute('data-ewbhxh'))
  const ldzc = isWzx
    ? [
      '1',
      '2',
      '35',
      '3',
      '4',
      '5',
      '8',
      '9',
      '36',
      '10',
      '11',
      '12', // 只读
    ]
    : [
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      '10',
      '11',
      '12',
      '13',
      '14',
    ];

  await fillC0019Grid(frameDoc, thisYearData, ldzc, true, 3);

  // 非流动资产
  const fldzc = isWzx
    ? [
      '14',
      '15',
      '16',
      '17',
      '18',
      '19',
      '20',
      '23',
      '24',
      '25',
      '26',
      '27',
      '28',
      '29',
      '30',
      '31',
      '32',
    ]
    : [
      '15',
      '16',
      '17',
      '18',
      '19',
      '20',
      '21',
      '22',
      '23',
      '24',
      '25',
      '26',
      '27',
      '28',
      '29',
      '30',
      '31',
      '32',
      '33',
      '34',
    ];
  await fillC0019Grid(frameDoc, thisYearData, fldzc, true, 16);

  // 流动负债
  const ldfz = isWzx
    ? ['1', '2', '35', '3', '4', '5', '6', '7', '10', '36', '11', '12', '13']
    : [
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      '10',
      '11',
      '12',
      '13',
      '14',
    ];

  await fillC0019Grid(frameDoc, thisYearData, ldfz, false, 35);

  // 非流动负债
  const fldfz = isWzx
    ? ['15', '16', '37', '38', '17', '19', '33', '20', '21', '22', '23']
    : ['15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26'];

  await fillC0019Grid(frameDoc, thisYearData, fldfz, false, 49);

  // 所有者权益(或股东权益)
  const syzqy = isWzx
    ? ['25', '39', '40', '41', '26', '27', '34', '42', '28', '29', '30', '32']
    : ['28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39'];
  await fillC0019Grid(frameDoc, thisYearData, syzqy, false, 61);
}

async function fillXqyZcfzGrid(frameDoc, data, xh, left = true, row = 3) {
  for (let i = 0; i < xh.length; i++) {
    let uid = `${row}`.padStart(2, '0');
    const dataItem = data.find((x) => x.reportItemUuid === `P11$${uid}`);
    row++;

    const ewbhxh = xh[i];

    const key1 = left ? 'zcfzb1' : 'zcfzb3';
    const key2 = left ? 'zcfzb2' : 'zcfzb4';

    // 期末余额
    if (dataItem.colValue1) {
      $(`[data-ewbhxh="${ewbhxh}"].${key1}`, frameDoc)
        .val(dataItem.colValue1)
        .trigger('input');
      await delay(50);
    }

    // 年初余额
    if (dataItem.colValue2) {
      $(`[data-ewbhxh="${ewbhxh}"].${key2}`, frameDoc)
        .val(dataItem.colValue2)
        .trigger('input');
      await delay(50);
    }
  }
}

/**
 * 填写资产负债表 小企业会计准则
 */
export async function fillXqyZcfz(data) {
  const thisYearData = data.data.balance;

  const layerDoc = $('.layui-layer-content iframe')[0].contentWindow.document;
  const frameDoc = $('iframe[name="xqyzcfzb"]', layerDoc)[0].contentWindow
    .document;

  // Array.from(document.querySelectorAll('[name="qmyeZc"]')).map(x=>x.getAttribute('data-ewbhxh'))
  const ldzc = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
    '13',
    '14',
    '15',
  ];

  await fillXqyZcfzGrid(frameDoc, thisYearData, ldzc, true, 3);

  // 非流动资产
  const fldzc = [
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
    '23',
    '24',
    '25',
    '26',
    '27',
    '28',
    '29',
    '30',
    '31',
  ];
  await fillXqyZcfzGrid(frameDoc, thisYearData, fldzc, true, 19);

  // 流动负债
  const ldfz = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'];

  await fillXqyZcfzGrid(frameDoc, thisYearData, ldfz, false, 36);

  // 非流动负债
  const fldfz = ['13', '14', '15', '16', '17', '18'];

  await fillXqyZcfzGrid(frameDoc, thisYearData, fldfz, false, 48);

  // 所有者权益(或股东权益)
  const syzqy = ['26', '27', '28', '29', '30', '31'];
  await fillXqyZcfzGrid(frameDoc, thisYearData, syzqy, false, 61);
}

/**
 * 填写 利润表 企业会计准则
 */
async function fillQyLrb(data, shouldFillLastYear) {
  const thisYearData = data.data.profit;
  const lastYearData = data.lastYearData.profit;

  const layerDoc = $('.layui-layer-content iframe')[0].contentWindow.document;
  // 是否是未执行
  let isWzx = true;
  let frame = $('iframe[name="C00120"]', layerDoc); // 未执行
  if (!frame || frame.length === 0) {
    isWzx = false;
    frame = $('iframe[name="A06894"]', layerDoc); // 已执行
  }
  const frameDoc = frame[0].contentWindow.document;

  // Array.from(document.querySelectorAll('.lrbBqjeList')).map(x=>x.getAttribute('id'))
  const bqCells = isWzx
    ? [
      'lrbxxForm_h1l2',
      'lrbxxForm_h2l2',
      'lrbxxForm_h3l2',
      'lrbxxForm_h4l2',
      'lrbxxForm_h5l2',
      'lrbxxForm_h37l2',
      'lrbxxForm_h6l2',
      'lrbxxForm_h38l2',
      'lrbxxForm_h39l2',
      'lrbxxForm_h40l2',
      'lrbxxForm_h41l2',
      'lrbxxForm_h42l2',
      'lrbxxForm_h43l2',
      'lrbxxForm_h7l2',
      'lrbxxForm_h33l2',
      'lrbxxForm_h11l2',
      'lrbxxForm_h12l2',
      'lrbxxForm_h13l2',
      'lrbxxForm_h15l2',
      'lrbxxForm_h16l2',
      'lrbxxForm_h17l2',
      'lrbxxForm_h35l2',
      'lrbxxForm_h36l2',
      'lrbxxForm_h22l2',
      'lrbxxForm_h23l2',
      'lrbxxForm_h24l2',
      'lrbxxForm_h25l2',
      'lrbxxForm_h26l2',
      'lrbxxForm_h27l2',
      'lrbxxForm_h28l2',
      'lrbxxForm_h29l2',
      'lrbxxForm_h30l2',
      'lrbxxForm_h31l2',
      'lrbxxForm_h32l2',
      'lrbxxForm_h19l2',
      'lrbxxForm_h20l2',
    ]
    : [
      'h1l2',
      'h2l2',
      'h3l2',
      'h4l2',
      'h5l2',
      'h6l2',
      'h7l2',
      'h8l2',
      'h9l2',
      'h10l2',
      'h11l2',
      'h12l2',
      'h13l2',
      'h14l2',
      'h15l2',
      'h16l2',
      'h17l2',
      'h18l2',
      'h19l2',
      'h20l2',
      'h21l2',
      'h22l2',
      'h23l2',
      'h24l2',
      'h25l2',
      'h26l2',
      'h27l2',
      'h28l2',
      'h29l2',
      'h30l2',
      'h31l2',
      'h32l2',
      'h33l2',
      'h34l2',
      'h35l2',
      'h36l2',
      'h37l2',
      'h38l2',
      'h39l2',
      'h40l2',
      'h41l2',
      'h42l2',
    ];
  // Array.from(document.querySelectorAll('.lrbSqjeList')).map(x=>x.getAttribute('id'))
  const sqCells = isWzx
    ? [
      'lrbxxForm_h1l3',
      'lrbxxForm_h2l3',
      'lrbxxForm_h3l3',
      'lrbxxForm_h4l3',
      'lrbxxForm_h5l3',
      'lrbxxForm_h37l3',
      'lrbxxForm_h6l3',
      'lrbxxForm_h38l3',
      'lrbxxForm_h39l3',
      'lrbxxForm_h40l3',
      'lrbxxForm_h41l3',
      'lrbxxForm_h42l3',
      'lrbxxForm_h43l3',
      'lrbxxForm_h7l3',
      'lrbxxForm_h33l3',
      'lrbxxForm_h11l3',
      'lrbxxForm_h12l3',
      'lrbxxForm_h13l3',
      'lrbxxForm_h15l3',
      'lrbxxForm_h16l3',
      'lrbxxForm_h17l3',
      'lrbxxForm_h35l3',
      'lrbxxForm_h36l3',
      'lrbxxForm_h22l3',
      'lrbxxForm_h23l3',
      'lrbxxForm_h24l3',
      'lrbxxForm_h25l3',
      'lrbxxForm_h26l3',
      'lrbxxForm_h27l3',
      'lrbxxForm_h28l3',
      'lrbxxForm_h29l3',
      'lrbxxForm_h30l3',
      'lrbxxForm_h31l3',
      'lrbxxForm_h32l3',
      'lrbxxForm_h19l3',
      'lrbxxForm_h20l3',
    ]
    : [
      'h1l3',
      'h2l3',
      'h3l3',
      'h4l3',
      'h5l3',
      'h6l3',
      'h7l3',
      'h8l3',
      'h9l3',
      'h10l3',
      'h11l3',
      'h12l3',
      'h13l3',
      'h14l3',
      'h15l3',
      'h16l3',
      'h17l3',
      'h18l3',
      'h19l3',
      'h20l3',
      'h21l3',
      'h22l3',
      'h23l3',
      'h24l3',
      'h25l3',
      'h26l3',
      'h27l3',
      'h28l3',
      'h29l3',
      'h30l3',
      'h31l3',
      'h32l3',
      'h33l3',
      'h34l3',
      'h35l3',
      'h36l3',
      'h37l3',
      'h38l3',
      'h39l3',
      'h40l3',
      'h41l3',
      'h42l3',
    ];

  let idx = 0;
  for (let i = 2; i < thisYearData.length; i++) {
    // 跳过空行 七、每股收益
    if (i === 36) {
      continue;
    }

    let uid = `${i}`.padStart(2, '0');
    uid = `P27$${uid}`;

    const thisData = thisYearData.find((x) => x.reportItemUuid === uid);
    if (thisData.colValue1) {
      const thisKey = bqCells[idx];
      const selector = isWzx ? `#${thisKey}` : `textarea[name="${thisKey}"]`;
      $(selector, frameDoc).val(thisData.colValue1).trigger('input');
      await delay(50);
    }

    // 是否需要填写上年数据
    if (shouldFillLastYear) {
      const lastData = lastYearData.find((x) => x.reportItemUuid === uid);
      if (lastData.colValue1) {
        const lastKey = sqCells[idx];
        const selector = isWzx ? `#${lastKey}` : `textarea[name="${lastKey}"]`;
        $(selector, frameDoc).val(lastData.colValue1).trigger('input');
        await delay(50);
      }
    }

    idx++;
  }
}

/**
 * 填写 利润表 小企业会计准则
 */
async function fillXqyLrb(data, shouldFillLastYear) {
  // 序号
  const xhArr = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
    '13',
    '14',
    '15',
    '16',
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
    '23',
    '24',
    '25',
    '26',
    '27',
    '28',
    '29',
    '30',
    '31',
    '32',
  ];

  const thisYearData = data.data.profit;
  const lastYearData = data.lastYearData.profit;

  const layerDoc = $('.layui-layer-content iframe')[0].contentWindow.document;
  const frameDoc = $('iframe[name="xqylrb"]', layerDoc)[0].contentWindow
    .document;

  for (let i = 1; i < xhArr.length; i++) {
    const xh = xhArr[i - 1];
    let uid = `${i + 1}`.padStart(2, '0'); // uuid 02开始
    uid = `P12$${uid}`;

    const thisData = thisYearData.find((x) => x.reportItemUuid === uid);
    if (thisData.colValue1) {
      $(`[data-ewbhxh="${xh}"].lrb1`, frameDoc)
        .val(thisData.colValue1)
        .trigger('input');
      await delay(50);
    }

    // 是否需要填写上年数据
    if (shouldFillLastYear) {
      const lastData = lastYearData.find((x) => x.reportItemUuid === uid);
      if (lastData.colValue1) {
        $(`[data-ewbhxh="${xh}"].lrb2`, frameDoc)
          .val(lastData.colValue1)
          .trigger('input');
        await delay(50);
      }
    }
  }
}

/**
 * 填写现金流量表 企业会计准则
 */
async function fillQyXjllb(data, shouldFillLastYear) {
  // Array.from(document.querySelectorAll('.xjllbBqjeList')).map(x=>x.getAttribute('id'))
  const bqCells = [
    'xjllbxxForm_h1l2',
    'xjllbxxForm_h2l2',
    'xjllbxxForm_h3l2',
    'xjllbxxForm_h4l2',
    'xjllbxxForm_h5l2',
    'xjllbxxForm_h6l2',
    'lrbxxForm_h7l2',
    'xjllbxxForm_h8l2',
    'xjllbxxForm_h9l2',
    'xjllbxxForm_h10l2',
    'xjllbxxForm_h11l2',
    'xjllbxxForm_h12l2',
    'xjllbxxForm_h13l2',
    'xjllbxxForm_h14l2',
    'xjllbxxForm_h15l2',
    'xjllbxxForm_h16l2',
    'xjllbxxForm_h17l2',
    'xjllbxxForm_h18l2',
    'xjllbxxForm_h19l2',
    'xjllbxxForm_h20l2',
    'xjllbxxForm_h21l2',
    'xjllbxxForm_h22l2',
    'xjllbxxForm_h23l2',
    'xjllbxxForm_h24l2',
    'xjllbxxForm_h25l2',
    'xjllbxxForm_h26l2',
    'xjllbxxForm_h27l2',
    'xjllbxxForm_h28l2',
    'xjllbxxForm_h29l2',
    'xjllbxxForm_h30l2',
    'xjllbxxForm_h31l2',
    'xjllbxxForm_h32l2',
    'xjllbxxForm_h33l2',
    'xjllbxxForm_h34l2',
    'xjllbxxForm_h35l2',
  ];
  // Array.from(document.querySelectorAll('.xjllbSqjeList')).map(x=>x.getAttribute('id'))
  const sqCells = [
    'xjllbxxForm_h1l3',
    'xjllbxxForm_h2l3',
    'xjllbxxForm_h3l3',
    'xjllbxxForm_h4l3',
    'xjllbxxForm_h5l3',
    'xjllbxxForm_h6l3',
    'lrbxxForm_h7l3',
    'xjllbxxForm_h8l3',
    'xjllbxxForm_h9l3',
    'xjllbxxForm_h10l3',
    'xjllbxxForm_h11l3',
    'xjllbxxForm_h12l3',
    'xjllbxxForm_h13l3',
    'xjllbxxForm_h14l3',
    'xjllbxxForm_h15l3',
    'xjllbxxForm_h16l3',
    'xjllbxxForm_h17l3',
    'xjllbxxForm_h18l3',
    'xjllbxxForm_h19l3',
    'xjllbxxForm_h20l3',
    'xjllbxxForm_h21l3',
    'xjllbxxForm_h22l3',
    'xjllbxxForm_h23l3',
    'xjllbxxForm_h24l3',
    'xjllbxxForm_h25l3',
    'xjllbxxForm_h26l3',
    'xjllbxxForm_h27l3',
    'xjllbxxForm_h28l3',
    'xjllbxxForm_h29l3',
    'lrbxxForm_h19l3',
    'xjllbxxForm_h31l3',
    'xjllbxxForm_h32l3',
    'xjllbxxForm_h33l3',
    'xjllbxxForm_h34l3',
    'xjllbxxForm_h35l3',
  ];

  const thisYearData = data.data.cash;
  const lastYearData = data.lastYearData.cash;

  const layerDoc = $('.layui-layer-content iframe')[0].contentWindow.document;
  const frameDoc = $('iframe[name="C00121"]', layerDoc)[0].contentWindow
    .document;

  let idx = 0;
  for (let i = 3; i < thisYearData.length; i++) {
    // 跳过空行
    if ([13, 26].includes(i)) {
      continue;
    }

    let uid = `${i}`.padStart(2, '0');
    uid = `P3$${uid}`;

    const thisData = thisYearData.find((x) => x.reportItemUuid === uid);
    if (thisData.colValue3) {
      const thisKey = bqCells[idx];
      $(`#${thisKey}`, frameDoc).val(thisData.colValue3).trigger('input');
      await delay(50);
    }

    if (shouldFillLastYear) {
      const lastData = lastYearData.find((x) => x.reportItemUuid === uid);
      if (lastData.colValue3) {
        const lastKey = sqCells[idx];
        $(`#${lastKey}`, frameDoc).val(lastData.colValue3).trigger('input');
        await delay(50);
      }
    }

    idx++;
  }
}

/**
 * 填写现金流量表 小企业会计准则
 */
async function fillXqyXjllb(data, shouldFillLastYear) {
  const thisYearData = data.data.cash;
  const lastYearData = data.lastYearData.cash;

  const layerDoc = $('.layui-layer-content iframe')[0].contentWindow.document;
  const frameDoc = $('iframe[name="xqyxjllb"]', layerDoc)[0].contentWindow
    .document;

  const xhArr = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '10',
    '12',
    '13',
    '14',
    '15',
    '16',
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
  ];

  let delta = 2;
  for (let i = 1; i <= xhArr.length; i++) {
    const xh = xhArr[i - 1];

    if ([8, 14].includes(i)) {
      delta += 1;
    }

    let uid = `${i + delta}`.padStart(2, '0');
    uid = `P13$${uid}`;

    const thisData = thisYearData.find((x) => x.reportItemUuid === uid);
    if (thisData.colValue1) {
      $(`[data-ewbhxh="${xh}"].xjllb1`, frameDoc)
        .val(thisData.colValue1)
        .trigger('input');
      await delay(50);
    }

    if (shouldFillLastYear) {
      const lastData = lastYearData.find((x) => x.reportItemUuid === uid);
      if (lastData.colValue1) {
        $(`[data-ewbhxh="${xh}"].xjllb2`, frameDoc)
          .val(lastData.colValue1)
          .trigger('input');
        await delay(50);
      }
    }
  }
}

async function fillInput_Month(data) {
  console.log(data);
  const { sheetType: sheet, institution } = data;
  const inputData = data.data[sheet];
  const ins = institution === '2013' ? 'xqykjzz' : 'qykjzz'
  if (sheet === 'cash') throw new Error('不支持的报表类型')
  if (ins === 'qykjzz') throw new Error('不支持的财报准则')
  const vk = CWBB_MONTH_JSON[ins][sheet];

  // 找到对应的iframe
  const layerDoc = $('.layui-layer-content iframe')[0].contentWindow.document;
  let iframeClass = ''
  if (ins === 'xqykjzz') {
    if (sheet === 'profit') {
      iframeClass = 'iframe[name="xqylrb"]'
    } else {
      iframeClass = 'iframe[name="xqyzcfzb"]'
    }
  } else {
    if (sheet === 'profit') {
      iframeClass = 'iframe[name="C00120"]'
    } else {
      iframeClass = 'iframe[name="C00119"]'
    }
  }
  const frameDoc = $(iframeClass, layerDoc)[0].contentWindow.document;
  // console.log(inputData)
  for (let k in vk) {
    let v = vk[k];
    let keys = k.split('_');
    const saasItem = inputData[v.replace('h', '')]
    let val = '1';
    let inpustClass = '';
    if (ins === 'xqykjzz' || (ins === 'qykjzz' && sheet === 'balance')) {
      if (k.includes('qmye') || k.includes('bnljje')) val = saasItem.colValue1;
      if (k.includes('ncye') || k.includes('byje')) val = saasItem.colValue2;
      inpustClass = `[data-ewbhxh="${keys[1]}"][name=${keys[0]}]`;
    } else if (ins === 'qykjzz' && sheet === 'profit') {
      if (k.includes('l2')) val = saasItem.colValue1;
      else val = saasItem.colValue2;
      inpustClass = `[name=${k}]`;
    }

    // // l2期末余额 l3年初余额

    const input = $(inpustClass, frameDoc);
    if (!input.attr('disabled')) {
      input.val(val || '0.00').trigger('input');
      await delay(50);
    }
  }
}

export async function fillTable(data, shouldFillLastYear, saasData) {
  let message = '填报成功 ';
  try {
    let isYearReport = saasData.isYearReport
    if (!isYearReport) {
      await fillInput_Month(data);
    } else {
      const { sheetType, institution } = data;
      const xqy = institution === '2013';
      switch (sheetType) {
        case 'balance': {
          if (xqy) {
            await fillXqyZcfz(data);
          } else {
            await fillQyZcfz(data);
          }
          break;
        }
        case 'profit': {
          if (xqy) {
            await fillXqyLrb(data, shouldFillLastYear);
          } else {
            await fillQyLrb(data, shouldFillLastYear);
          }
          break;
        }
        case 'cash': {
          if (xqy) {
            await fillXqyXjllb(data, shouldFillLastYear);
          } else {
            await fillQyXjllb(data, shouldFillLastYear);
          }
          break;
        }
        default:
          break;
      }
    }
  } catch (err) {
    message = err.message || '填报失败';
    console.error(err);
    await delay(2000)
  } finally {
    postMsg('fillInputDone', { message });
  }
}
